﻿using ReaderB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ZK.HardWareHelp
{
    /// <summary>
    /// 明华室内读卡器（串口）
    /// </summary>
    public class MHSNReader
    {
        private byte fComAdr = 0xff; //当前操作的ComAdr
        private int frmcomportindex;
        private byte[] fPassWord = new byte[4];
        private byte MaskLen;
        private byte MaskFlag;
        private byte Maskadr;
        private int ferrorcode;

        Timer timer = new Timer();
        private System.Windows.Forms.Timer Timer_Test_;
        private byte fBaud;
        private int fOpenComIndex; //打开的串口索引号
        private bool ComOpen = false;
        private int fCmdRet = 30; //所有执行指令的返回值
        private Common.HaredWareCommonM mHSNReader;
        private int port;
        /// <summary>
        /// 获取卡号
        /// </summary>
        /// <returns></returns>
        public string GetCardNum()
        {
            int CardNum = 0;
            int Totallen = 0;
            byte[] EPC = new byte[5000];
            string temps;
            byte AdrTID = 0;
            byte LenTID = 0;
            byte TIDFlag = 0;
            int? res;
            ListViewItem aListItem = new ListViewItem();
            res = StaticClassReaderB.Inventory_G2(ref fComAdr, AdrTID, LenTID, TIDFlag, EPC, ref Totallen, ref CardNum, frmcomportindex);
            if ((res == 1) | (res == 2) | (res == 3) | (res == 4) | (res == 0xFB))//代表已查找结束，
            {
                byte[] daw = new byte[Totallen];
                Array.Copy(EPC, daw, Totallen);
                temps = ByteArrayToHexString(daw);
                if (!string.IsNullOrEmpty(temps))
                {
                    return temps.Substring(2);
                }
            }
            return "";
        }
        public MHSNReader()
        {
            try
            {
                mHSNReader = Common.IConfig.GetSetMHSNReader;
                port = Convert.ToInt32(mHSNReader.PortName.Substring(3, mHSNReader.PortName.Length - 3));
                fComAdr = Convert.ToByte("FF", 16); // $FF;
                int openresult, i;
                for (i = 6; i >= 0; i--)
                {
                    fBaud = Convert.ToByte(i);
                    if (fBaud == 3)
                        continue;
                    openresult = StaticClassReaderB.OpenComPort(port, ref fComAdr, fBaud, ref frmcomportindex);
                    fOpenComIndex = frmcomportindex;
                    if (openresult == 0x35)
                    {
                        //MessageBox.Show("串口已打开", "信息提示");
                        return;
                    }
                    if (openresult == 0)
                    {
                        ComOpen = true;
                        //Button3_Click(sender, e); //自动执行读取写卡器信息
                        //if (fBaud > 3)
                        //{
                        //    ComboBox_baud.SelectedIndex = Convert.ToInt32(fBaud - 2);
                        //}
                        //else
                        //{
                        //    ComboBox_baud.SelectedIndex = Convert.ToInt32(fBaud);
                        //}
                        if ((fCmdRet == 0x35) || (fCmdRet == 0x30))
                        {
                            ComOpen = false;
                            //MessageBox.Show("串口通讯错误", "信息提示");
                            StaticClassReaderB.CloseSpecComPort(frmcomportindex);
                            return;
                        }
                        //RefreshStatus();
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Common.SimpleLog.WriteLog("室内读卡器构造函数不带参 " + ex.ToString());
                Common.DelegateHelper.InfoMessageEvent?.Invoke("室内读卡器初始化失败！");
            }


            //timer.Interval = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("CardReaderTime"));
            //timer.Enabled = true;
            //timer.Tick += new EventHandler(timer1EventProcessor);//添加事件
        }

        public MHSNReader(string portName)
        {
            try
            {
                port = Convert.ToInt32(portName.Substring(3, portName.Length - 3));
                fComAdr = Convert.ToByte("FF", 16); // $FF;
                int openresult, i;
                for (i = 6; i >= 0; i--)
                {
                    fBaud = Convert.ToByte(i);
                    if (fBaud == 3)
                        continue;
                    openresult = StaticClassReaderB.OpenComPort(port, ref fComAdr, fBaud, ref frmcomportindex);
                    fOpenComIndex = frmcomportindex;
                    if (openresult == 0x35)
                    {
                        //MessageBox.Show("串口已打开", "信息提示");
                        return;
                    }
                    if (openresult == 0)
                    {
                        ComOpen = true;
                        //Button3_Click(sender, e); //自动执行读取写卡器信息
                        //if (fBaud > 3)
                        //{
                        //    ComboBox_baud.SelectedIndex = Convert.ToInt32(fBaud - 2);
                        //}
                        //else
                        //{
                        //    ComboBox_baud.SelectedIndex = Convert.ToInt32(fBaud);
                        //}
                        if ((fCmdRet == 0x35) || (fCmdRet == 0x30))
                        {
                            ComOpen = false;
                            //MessageBox.Show("串口通讯错误", "信息提示");
                            StaticClassReaderB.CloseSpecComPort(frmcomportindex);
                            return;
                        }
                        //RefreshStatus();
                        break;
                    }
                }
            }
            catch (Exception ex)
            {

                Common.SimpleLog.WriteLog("室内读卡器构造函数带参数 " + ex.ToString());
                Common.DelegateHelper.InfoMessageEvent?.Invoke("室内读卡器初始化失败！");
            }


            //timer.Interval = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("CardReaderTime"));
            //timer.Enabled = true;
            //timer.Tick += new EventHandler(timer1EventProcessor);//添加事件
        }

        /// <summary>
        /// 读卡
        /// </summary>
        public void ReadCard()
        {
            Inventory();
        }

        private void timer1EventProcessor(object sender, EventArgs e)
        {
            Inventory();
        }
        /// <summary>
        /// 写卡
        /// </summary>
        /// <param name="oldStr">老卡号</param>
        /// <param name="newStr">新卡号</param>
        public void WriteCard(string oldStr, string newStr)
        {
            int? res;
            byte WordPtr, ENum;
            byte Mem = 1;//保留区0 epc1 tid2 用户区3 
            string s2;
            byte WNum = 0;
            byte Writedatalen = 6;
            ENum = Convert.ToByte(oldStr.Length / 4);
            byte[] EPC = new byte[ENum];
            EPC = HexStringToByteArray(oldStr);
            s2 = newStr;
            WNum = Convert.ToByte(s2.Length / 4);
            byte[] Writedata = new byte[WNum * 2];
            Writedata = HexStringToByteArray(s2);
            WordPtr = Convert.ToByte("2", 16);
            fPassWord = HexStringToByteArray("00000000");
            Maskadr = Convert.ToByte("00", 16);
            MaskLen = Convert.ToByte("00", 16);
            MaskFlag = 0;
            int WrittenDataNum = 0;
            byte EPClength = 0;
            EPClength = Convert.ToByte(ENum * 2);

            WordPtr = 1;
            Writedatalen = 8;
            Writedata = HexStringToByteArray("1800" + s2);

            timer.Stop();
            res = StaticClassReaderB.WriteCard_G2(
                ref fComAdr,
                EPC,
                Mem,
                WordPtr,
                Writedatalen,
                Writedata,
                fPassWord,
                Maskadr,
                MaskLen,
                MaskFlag,
                WrittenDataNum,
                EPClength,
                ref ferrorcode,
                frmcomportindex
                );
            if (res != 0)
            {
                Common.Log4.LogManage.WriteErr("读卡器写卡失败 错误代码" + res);
                Common.MessageDialog.MessageBoxShow("读卡器写卡失败，原因未知", "读卡器");
            }
            timer.Start();
        }


        public void CloseRes()
        {
            int res;
            timer.Stop();
            timer.Dispose();
            fCmdRet = StaticClassReaderB.CloseSpecComPort(port);
            if (fCmdRet != 0)
            {
                Common.Log4.LogManage.WriteErr("室内读卡器关闭失败错误代码" + fCmdRet);
                Common.MessageDialog.MessageBoxShow("室内读卡器关闭失败，原因未知", "室内读卡器");
            }

        }
        private void Inventory()
        {
            int CardNum = 0;
            int Totallen = 0;
            byte[] EPC = new byte[5000];
            string temps;
            byte AdrTID = 0;
            byte LenTID = 0;
            byte TIDFlag = 0;
            int? res;
            ListViewItem aListItem = new ListViewItem();
            res = StaticClassReaderB.Inventory_G2(ref fComAdr, AdrTID, LenTID, TIDFlag, EPC, ref Totallen, ref CardNum, frmcomportindex);
            if ((res == 1) | (res == 2) | (res == 3) | (res == 4) | (res == 0xFB))//代表已查找结束，
            {
                byte[] daw = new byte[Totallen];
                Array.Copy(EPC, daw, Totallen);
                temps = ByteArrayToHexString(daw);
                if (!string.IsNullOrEmpty(temps))
                {
                    Common.DelegateHelper.MWSNMessageReceivedEvent?.Invoke(temps.Substring(2));
                }
            }
        }
        private string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
            return sb.ToString().ToUpper();

        }
        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

    }
}
